package android.gpsmessenger;

import java.io.*;
import java.util.*;

import android.util.Xml;
import android.app.Activity;

import org.xmlpull.v1.XmlSerializer;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class ContactManager
{
	private String _xmlFile;
	private Activity _activity;
	
	public ContactManager(Activity activity)
	{
		_activity = activity;
		_xmlFile = "/contacts.xml";
	}
	
	public ContactManager()
	{
		_activity = new Activity();
		_xmlFile = "/contacts.xml";
	}
	public void setActivity(Activity activity)
	{
		_activity = activity;
	}
	
 	public ContactList load()
	{
		String id, name, phone, email;
		Contact newContact ;    
		ContactList contacts = new ContactList();
		XmlPullParser parser = Xml.newPullParser();
		try 
		{
			File myFile = new File(_activity.getFilesDir().getAbsolutePath() + _xmlFile);
			InputStream in = new FileInputStream(myFile);
			
			parser.setInput(in, null);
			
			while (parser.getEventType() != XmlPullParser.END_DOCUMENT)
			{
				if(parser.getEventType() == XmlPullParser.START_TAG && 
		                        parser.getName().equalsIgnoreCase("contact"))
				{
					id = parser.getAttributeValue(null, "id");
					name = parser.getAttributeValue(null, "name");
		            phone = parser.getAttributeValue(null, "phone");
		            email = parser.getAttributeValue(null, "email");
		            
		            newContact = new Contact(name, phone, email, id);
		            
		            if 	 (id.equals("sos"))
						contacts.setSOSContact(newContact);
					else
						contacts.add(newContact); 	            
		         }
		         parser.next();
		     }
		}  
		catch (IOException e) {e.printStackTrace();} 
		catch (XmlPullParserException e) {e.printStackTrace();}        
	
		return contacts;
	}
 	
	public void save(ContactList contacts)
	{	
		try
		{ 	
			String str = writeXML(contacts);
			File myFile = new File(_activity.getFilesDir().getAbsolutePath() + _xmlFile);
			
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =  new OutputStreamWriter(fOut);
            myOutWriter.append(str);
            myOutWriter.close();
            fOut.close();
		}
		catch(IOException ioe) {ioe.printStackTrace();}		
	}
	
 	private String writeXML(ContactList contacts){
 	    XmlSerializer serializer = Xml.newSerializer();
 	    StringWriter writer = new StringWriter();
 	    try {
 	        serializer.setOutput(writer);
 	        serializer.startDocument("UTF-8", true);
 	        serializer.startTag("", "contacts");
 	        
 	        serializer.startTag("", "contact");
 	        serializer.attribute("", "id", "sos");
 	        serializer.attribute("", "name", contacts.getSOSContact().getName());
 	        serializer.attribute("", "phone", contacts.getSOSContact().getPhone());
 	        serializer.attribute("", "email", contacts.getSOSContact().getEmail());
 	        serializer.endTag("", "contact");
 	        
 	        Iterator<Contact> helpContactIterator = contacts.helpContactsIterator();
 	        while(helpContactIterator.hasNext())
 	        {
 	        	Contact hc = (Contact) helpContactIterator.next(); 	
 	        	
 	        	serializer.startTag("", "contact");
 	 	        serializer.attribute("", "id", "help");
 	 	        serializer.attribute("", "name", hc.getName());
 	 	        serializer.attribute("", "phone", hc.getPhone());
 	 	        serializer.attribute("", "email", hc.getEmail()); 
 	 	        serializer.endTag("", "contact");
 	        }
 	        
 	        Iterator<Contact> friendContactIterator = contacts.friendContactsIterator();
 	        while(friendContactIterator.hasNext())
 	        {
 	        	Contact fc = (Contact) friendContactIterator.next();
	        	serializer.startTag("", "contact");
 	 	        serializer.attribute("", "id", "friend");
 	 	        serializer.attribute("", "name", fc.getName());
 	 	        serializer.attribute("", "phone", fc.getPhone());
 	 	        serializer.attribute("", "email", fc.getEmail()); 
 	 	        serializer.endTag("", "contact");
 	        }
 	        
 	        serializer.endTag("", "contacts");
 	        serializer.endDocument();
 	        return writer.toString();
 	    } 
 	    catch (Exception e) {throw new RuntimeException(e);} 
 	}
}

